package com.ruoyi.common.utils;

import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.Marshaller;
import jakarta.xml.bind.Unmarshaller;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.io.*;
import java.nio.charset.StandardCharsets;

public class XmlUtil {

    /**
     * JavaBean转换成xml
     *
     * @param obj      javaBean
     * @param encoding 字符集
     * @return
     */
    public static String convertToXml(Object obj, String encoding) {
        String result = null;
        try {
            JAXBContext context = JAXBContext.newInstance(obj.getClass());
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);

            StringWriter writer = new StringWriter();
            marshaller.marshal(obj, writer);
            result = writer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     * xml转换成JavaBean
     *
     * @param xml xml字符串
     * @param c   javaBean
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T convertToJavaBean(String xml, Class<T> c) {
        T t = null;
        try {
            JAXBContext context = JAXBContext.newInstance(c);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            t = (T) unmarshaller.unmarshal(new StringReader(xml));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return t;
    }

    private static class CustomHandler extends DefaultHandler {
        private StringBuilder xmlContent = new StringBuilder();
        private String currentElement;

        public String getXmlContent() {
            return xmlContent.toString();
        }

        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
            System.out.println("<" + qName + ">");
            for (int i = 0; i < attributes.getLength(); i++) {
                System.out.println(attributes.getQName(i) + ":"
                        + attributes.getValue(i));
            }
            currentElement = qName;
            // 添加开始标记
            xmlContent.append("<").append(qName);
            for (int i = 0; i < attributes.getLength(); i++) {
                String attributeName = attributes.getQName(i);
                String attributeValue = attributes.getValue(i);
                xmlContent.append(" ").append(attributeName).append("=\"").append(attributeValue).append("\"");
            }
            xmlContent.append(">");
        }

        @Override
        public void endElement(String uri, String localName, String qName) throws SAXException {
            System.out.println("<" + qName + ">");
            currentElement = null;
            // 添加结束标记
            xmlContent.append("</").append(qName).append(">");
        }

        @Override
        public void characters(char[] ch, int start, int length) throws SAXException {
            System.out.println(new String(ch, start, length));
            if (currentElement != null && currentElement.equals("age")) {
                // 修改age节点的文本内容
                xmlContent.append("80");
            } else {
                xmlContent.append(ch, start, length);
            }
        }
    }


    /**
     * @param file xml文件
     * @return javaBean
     * @throws Exception 异常
     */
    public static <T> T convertTOJavaBean(File file, Class<T> c) throws IOException {

        try (FileInputStream fis = new FileInputStream(file);
             InputStreamReader isr = new InputStreamReader(fis, StandardCharsets.UTF_8);
             BufferedReader br = new BufferedReader(isr);) {
            StringBuffer xml = new StringBuffer();
            String line;
            while ((line = br.readLine()) != null) {
                xml.append(line);
                xml.append("\r\n");
            }
            String x = xml.toString();
            x = x.replaceAll(">\r\n", ">");
            x = x.replaceAll("\r\n", "&#xa;");
            x = x.replaceFirst("&#xa;", "");
            return XmlUtil.convertToJavaBean(x, c);
        }

    }


}


